<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\facade\Session;
use think\Request;
use think\Cookie;
use think\Validate;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class Login extends Controller{
	public $company=[];  //定义公司数组
	public function _initialize() {
        parent::_initialize();
    }

	//代理登录界面

	public function index(){
		if(session('central_admin')){
			$this->redirect('admin/index/index');
        }
        
        $this->assign('usermember',cookie('usermember'));
		return $this->fetch();
	}

	public function login(){
		
        if($this->request->isPost()) {
            
            //是登录操作
            $post = $this->request->post();
			
			
			$rule = [
			    'name'  => 'require|alphaDash',
			    'password'   => 'require',
			    'captcha' => 'require|captcha',
			];
			
			$msg = [
			    'name.require' 		=> '用户名不能为空',
			    'name.alphaDash'	=> '用户名格式只能是字母、数字、——或_',
			    'password.require'  => '密码不能为空',
			    'captcha.require'  	=> '验证码不能为空',
			    'captcha.captcha'   => '验证码不正确',
			];
			$validate   = Validate::make($rule,$msg);
            $handle_url = $this->request->module() . '/' . $this->request->controller() . '/' . $this->request->action();
            //验证部分数据合法性
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $name = Db::name('admin')->where(['name'=>$post['name'],'type'=>1])->find();
            
            if(empty($name)) {
                //不存在该用户名
                return $this->error('用户名不存在');
            } else {
                //验证密码
                $post['password'] = password($post['password']);
                
                if($name['password'] != $post['password']) {
                    return $this->error('密码错误');
                } else {
                    //是否记住账号
                    if(!empty($post['remember']) and $post['remember'] == 1) {
                        //检查当前有没有记住的账号
                        if(Cookie::has('usermember')) {
                            Cookie::delete('usermember');
                        }
                        
                        //保存新的
                        Cookie::forever('usermember',$post['name']);
                    } else {
                        //未选择记住账号，或属于取消操作
                        if(cookie('usermember')) {
                            Cookie::delete('usermember');
                        }
                    }
                    Session::set("central_admin",$name['id']); //保存新的
                    Session::set("central_cate_id",$name['admin_cate_id']); //保存新的
                    //记录登录时间和ip
                    Db::name('admin')->where(['id'=>$name['id'],'type'=>1])->update(['login_ip' =>$this->request->ip(),'login_time' => time()]);
                    return $this->success('登录成功,正在跳转...','admin/login/index');
                }
            }
        }
        
    }

	/**
     * logout 退出登录
     * user: zhanghaitao
     * @return array error_array[error_msg, url]
     */
	public function logout(){
		$handle_url = $this->request->module() . '/' . $this->request->controller() . '/' . $this->request->action();
		// add_user_log(session('user_id'),'账号：'.session('user')['account'].'【退出登录】',$handle_url,0,session('user')['c_id']);
		session('central_admin',null);
		session('central_cate_id',null);
        return $this->success('正在退出...','admin/login/index');
    }


    private function get_token($uid)
    {
		$time = time();
		$token = (new Builder())->setHeader('alg','HS256')
		//配置发行者
		->setIssuer("jwtTest")
		//配置Audience
		->setAudience("php")
		//配置令牌发出的时间（签发时间）
		->setIssuedAt($time)
		//配置令牌该时间之前不接收处理该Token
		->setNotBefore($time)
		//配置令牌到期的时间
		->setExpiration($time + 7200)
		//配置一个自定义uid声明
		->set('uid',$uid)
		//使用sha256进行签名,密钥为123456
		->sign(new Sha256(),"123456")
		//获取token
        ->getToken();
        
        $token = $token->getTokens();
        return $token;
    }
}

?>